package com.ydgk.servlet;

import com.alibaba.fastjson.JSON;
import com.ydgk.bean.Book;
import com.ydgk.dao.BookDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;

@WebServlet(name = "PagingAjaxServlet", urlPatterns = "/PagingAjaxServlet.action")
public class PagingAjaxServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String pn = request.getParameter("pageNumber");

        int pageNumber=1;

        try {
            pageNumber = Integer.parseInt(pn);
        }catch (NumberFormatException e){
            pageNumber=1;
        }

        BookDao bookDao = new BookDao();

        int maxPage = bookDao.maxPage("book");

        if(pageNumber < 1){
            pageNumber=1;
        }

        if(pageNumber>maxPage){
            pageNumber = maxPage;
        }

        List<Book> bookList = bookDao.paging(pageNumber);
        HashMap map = new HashMap();
        map.put("pageNumber",pageNumber);
        map.put("maxPage",maxPage);
        map.put("bookList",bookList);

        String str = JSON.toJSONString(map);

        PrintWriter out = response.getWriter();
        out.print(str);
    }


}
